<template>
  <div class="app-container">
    <el-form ref="form" inline :model="form" class="form-options" label-width="100px">
      <el-form-item label="用户名称">
        <el-autocomplete
          ref="nameRef"
          v-model="form.name"
          placeholder="请输入用户名称"
          :fetch-suggestions="querySearchName"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectName"
          @clear="clickClearnameRef"/>
      </el-form-item>
      <el-form-item label="登录账号">
        <el-autocomplete
          ref="userNameRef"
          v-model="form.userName"
          placeholder="请输入登录账号"
          :fetch-suggestions="querySearchUserName"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectUserName"
          @clear="clickClearuserNameRefs"/>
      </el-form-item>
      <el-form-item label="角色名称">
        <el-autocomplete
          ref="roleNameRef"
          v-model="form.roleName"
          placeholder="请输入角色名称"
          :fetch-suggestions="querySearchRole"
          :trigger-on-focus="false"
          clearable
          @select="handleSelectRole"
          @clear="clickClearroleNameRef"/>
      </el-form-item>
      <div class="btns">
        <el-button type="primary" v-permission="['sys_manage_user_query']" @click="onQuery">查询</el-button>
        <el-button type="primary" v-permission="['sys_manage_user_add']" @click="onAdd">新建</el-button>
        <el-button type="danger" v-permission="['sys_manage_user_del']" @click="onDelete">删除</el-button>
      </div>
    </el-form>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      header-cell-class-name="table-header"
      style="width: 100%;margin-top: 20px">
      <el-table-column
        type="selection"
        width="50">
      </el-table-column>
      <el-table-column
        label="序号"
        type="index"
        width="50">
      </el-table-column>
      <el-table-column
        prop="name"
        label="用户名称">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="登录账号">
      </el-table-column>
      <el-table-column
        prop="roleName"
        label="角色">
      </el-table-column>
      <el-table-column
        prop="jobTitle"
        label="职位">
      </el-table-column>
      <!-- <el-table-column
        prop="organizationName"
        label="部门">
      </el-table-column> -->
      <el-table-column
        prop="mail"
        label="邮箱">
      </el-table-column>
      <el-table-column
        prop="phone"
        label="电话">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间">
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template slot-scope='scope'>
          <el-button type="primary" v-permission="['sys_manage_user_edit']" @click="handleOperateClick(scope.row,'编辑')">
            编辑
          </el-button>
          <el-button type="danger" v-permission="['sys_manage_user_del']" @click="handleOperateClick(scope.row,'删除')">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div style="text-align: right;margin-top: 20px">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 15, 30]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <el-dialog
      center
      :title="dialogTitle"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="420px">
      <el-form ref="ruleForm" :model="dataForm" :rules="$rules.userRules" label-width="100px">
        <el-form-item label="用户名称" prop="name">
          <el-input v-model="dataForm.name" style="width: 250px" placeholder="请输入用户名称" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="userName" v-if="dialogTitle=='新增用户'">
          <el-input v-model="dataForm.userName" style="width: 250px" placeholder="请输入登录账号（默认密码123456）"></el-input>
        </el-form-item>
        <el-form-item label="登录账号" prop="userName2" v-else>
          <el-input v-model="dataForm.userName2" style="width: 250px" placeholder="请输入登录账号" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="roleId">
          <el-select v-model="dataForm.roleId" style="width: 250px" filterable placeholder="请选择角色">
            <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位" prop="jobTitle">
          <el-input v-model="dataForm.jobTitle" style="width: 250px" placeholder="请输入职位" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="mail">
          <el-input v-model="dataForm.mail" style="width: 250px" placeholder="请输入邮箱" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="dataForm.phone" style="width: 250px" placeholder="请输入电话" maxlength="20"></el-input>
        </el-form-item>
        <!-- <el-form-item label="所属部门" prop="organizationId">
          <el-select v-model="dataForm.organizationId" style="width: 250px" filterable placeholder="请选择所属部门">
            <el-option
              v-for="item in organizationOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="所管仓库" prop="warehouseList">
          <el-select v-model="dataForm.warehouseList" multiple style="width: 250px" filterable placeholder="请选择所管仓库">
            <el-option
              v-for="item in warehouseOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item> -->
      </el-form>
      <span slot="footer">
        <el-button type="primary" v-if="dialogTitle == '新增用户'" @click="saveData()">保存</el-button>
        <el-button type="primary" v-else @click="editData()">保存</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, deleteUser, updateUser, addUser, getRoles, getOrganizations } from '@/api/user'
import { getWarehouse } from '@/api/warehouse'

export default {
  name: 'UserManage',
  data() {
    return {
      currentPage: 1,
      total: 0,
      pageSize: 10,
      form: {
        roleName: '',
        userName: '',
        name: ''
      },
      props: { multiple: false, value: 'id', label: 'moduleName' },
      tableData: [],
      multipleSelection: [],
      dataForm: {
        name: '',
        userName: '',
        userName2: '',
        roleId: '',
        jobTitle: '',
        mail: '',
        phone: '',
        // organizationId: '',
        // warehouseList: ''
      },
      dialogTitle: '新增用户',
      dialogVisible: false,
      roleOptions: [],
      warehouseOptions: [],
      organizationOptions: []
    }
  },
  created() {
    this.onQuery()
  },
  methods: {
    handleSizeChange: function(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getTableData()
    },
    handleCurrentChange: function(val) {
      this.currentPage = val
      this.getTableData()
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    handleOperateClick(row, tag) {
      if (tag == '删除') {
        this.$confirm('确认删除此条数据?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }).then(() => {
          this.handleDelete([{ userId: row.userId }])
        })
      } else {
        const a = new Promise(resolve => {
          getRoles({}).then(res => {
            resolve(res.resultData)
          })
        })
        const b = new Promise(resolve => {
          getWarehouse({}).then(res => {
            resolve(res.resultData)
          })
        })
        const c = new Promise(resolve => {
          getOrganizations({}).then(res => {
            resolve(res.resultData)
          })
        })
        Promise.all([a, b, c]).then(res => {
          this.roleOptions = res[0]
          this.warehouseOptions = res[1]
          this.organizationOptions = res[2]
          this.dataForm = {
            userId: row.userId,
            name: row.name,
            userName: row.userName,
            userName2: row.userName,
            roleId: row.roleId,
            jobTitle: row.jobTitle,
            mail: row.mail,
            phone: row.phone,
            // organizationId: Number(row.organizationId),
            // warehouseList: row.warehouseList
          }
          this.dialogVisible = true
          this.dialogTitle = '编辑用户'
        })
      }
    },
    /**
     * 模糊查询用户账号
     * @param queryString
     * @param cb
     */
    querySearchUserName: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    /**
     * 选择用户账号
     * @param item
     */
    handleSelectUserName(item) {
      // console.log(item)
    },
    /**
     * 模糊查询用户名称
     * @param queryString
     * @param cb
     */
    querySearchName: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    /**
     * 选择用户名称
     * @param item
     */
    handleSelectName(item) {
      // console.log(item)
    },
    clickClearnameRef(){
      this.$nextTick(() => {
        if (this.$refs.nameRef) {
          this.$refs.nameRef.activated = true;
        }
      });
    },
    clickClearuserNameRefs(){
      this.$nextTick(() => {
        if (this.$refs.userNameRef) {
          this.$refs.userNameRef.activated = true;
        }
      });
    },
    clickClearroleNameRef(){
      this.$nextTick(() => {
        if (this.$refs.roleNameRef) {
          this.$refs.roleNameRef.activated = true;
        }
      });
    },
    /**
     * 模糊查询角色
     * @param queryString
     * @param cb
     */
    querySearchRole: function(queryString, cb) {
      // 调用 callback 返回建议列表的数据
      const results = []
      cb(results)
    },
    /**
     * 选择角色
     * @param item
     */
    handleSelectRole(item) {
      // console.log(item)
    },
    getTableData() {
      const param = { page: this.currentPage, rows: this.pageSize }
      Object.assign(param, this.form)
      getUsers(param).then(res => {
        this.tableData = res.rows
        this.total = res.total
        this.multipleSelection = []
      })
    },
    handleDelete(ids) {
      deleteUser(ids).then(res => {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.tableData = []
        this.getTableData()
      })
    },
    saveData() {
      const _this = this
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          addUser(_this.dataForm).then(response => {
            if (response.success) {
              _this.$message({
                message: '新增成功',
                type: 'success'
              })
              _this.dialogVisible = false
              _this.onQuery()
            }
          })
        } else {
          return false
        }
      })
    },
    editData() {
      const _this = this
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          _this.dataForm.userName = _this.dataForm.userName2
          updateUser(_this.dataForm).then(response => {
            if (response.success) {
              _this.$message({
                message: '更新成功',
                type: 'success'
              })
              _this.dialogVisible = false
              _this.getTableData()
            }
          })
        } else {
          return false
        }
      })
    },
    onQuery() {
      this.currentPage = 1
      this.getTableData()
    },
    onDelete() {
      if (!this.multipleSelection || this.multipleSelection.length === 0) {
        this.$message.error('请选择需要删除的数据')
        return
      }
      const ids = []
      this.multipleSelection.forEach(item => {
        ids.push({ userId: item.userId })
      })
      this.$confirm('确认删除选中的数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消'
      }).then(() => {
        this.handleDelete(ids)
      })
    },
    onAdd() {
      const a = new Promise(resolve => {
        getRoles({}).then(res => {
          resolve(res.resultData)
        })
      })
      const b = new Promise(resolve => {
        getWarehouse({}).then(res => {
          resolve(res.resultData)
        })
      })
      const c = new Promise(resolve => {
        getOrganizations({}).then(res => {
          resolve(res.resultData)
        })
      })
      Promise.all([a, b, c]).then(res => {
        this.roleOptions = res[0]
        this.warehouseOptions = res[1]
        this.organizationOptions = res[2]
        this.dataForm = {
          name: '',
          userName: '',
          userName2: '',
          roleId: '',
          jobTitle: '',
          mail: '',
          phone: '',
          // organizationId: '',
          // warehouseList: ''
        }
        this.dialogVisible = true
        this.dialogTitle = '新增用户'
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.line {
  text-align: center;
}
</style>

